/**
 * * 生成一个不重复的ID
 * @param { Number } randomLength
 */
export const getUUID = (randomLength: number = 10) => {
	return "id_" + Number(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36);
};
export const evalFn = (fn: string) => {
	const Fun = Function; // 一个变量指向Function，防止前端编译工具报错
	return new Fun("return " + fn)();
};
/**
 * * JSON反序列化，支持函数和 undefined
 * @param data
 */
export const JSONParse = (data: string) => {
	if (data.trim() === "") return;
	return JSON.parse(data, (k, v) => {
		// // 过滤函数字符串
		// if (excludeParseEventKeyList.includes(k)) return v
		// // 过滤函数值表达式
		// if (typeof v === 'string') {
		//   const someValue = excludeParseEventValueList.some(excludeValue => v.indexOf(excludeValue) > -1)
		//   if (someValue) return v
		// }
		if (k !== "formatter") {
			return v;
		}
		// 还原函数值
		if (typeof v === "string" && v.indexOf && (v.indexOf("function") > -1 || v.indexOf("=>") > -1)) {
			return evalFn(`(function(){return ${v}})()`);
		} else if (typeof v === "string" && v.indexOf && v.indexOf("return ") > -1) {
			const baseLeftIndex = v.indexOf("(");
			if (baseLeftIndex > -1) {
				const newFn = `function ${v.substring(baseLeftIndex)}`;
				return evalFn(`(function(){return ${newFn}})()`);
			}
		}
		return v;
	});
};
/**
 * * JSON序列化，支持函数和 undefined
 * @param data
 */
export const JSONStringify = <T>(data: T) => {
	return JSON.stringify(
		data,
		(_key, val) => {
			// 处理函数丢失问题
			if (typeof val === "function") {
				return `${val}`;
			}
			// 处理 undefined 丢失问题
			if (typeof val === "undefined") {
				return null;
			}
			return val;
		},
		2
	);
};
